package com.hanxiaozhang.threadbase1ndedition.no4lock;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 〈一句话功能简述〉<br>
 * 〈在等待时间之内可以被其它线程唤醒，等待时间一过该线程会自动唤醒，和别的线程争抢锁资源〉
 *
 * @author hanxinghua
 * @create 2021/11/12
 * @since 1.0.0
 */
public class No6ReentrantLockAwaitUntil {


    public static void main(String[] args) throws InterruptedException {

        No6ReentrantLockAwaitUntil example = new No6ReentrantLockAwaitUntil();

        new Thread(example::waitMethod).start();
        TimeUnit.SECONDS.sleep(2);
        new Thread(example::notifyMethod).start();

    }


    private ReentrantLock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();

    public void waitMethod() {
        Calendar calendarRef = Calendar.getInstance();
        calendarRef.add(Calendar.SECOND, 10);
        lock.lock();
        try {
            System.out.println("wait begin timer = " + System.currentTimeMillis());
            condition.awaitUntil(calendarRef.getTime());
            System.out.println("wait end timer =" + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void notifyMethod() {

        Calendar calendarRef = Calendar.getInstance();
        calendarRef.add(Calendar.SECOND, 10);
        lock.lock();
        try {
            System.out.println("notify begin timer = " + System.currentTimeMillis());
            condition.signalAll();
            System.out.println("notify end timer = " + System.currentTimeMillis());
        } finally {
            lock.unlock();
        }

    }



}
